package com.example.home.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.example.common.viewmodel.BaseViewModel
import com.example.entity.BaseEntity
import com.example.entity.NetDataEntity

import com.example.home.entity.discover.Banner2CardEntity
import com.example.home.entity.discover.BrieCardEntity
import com.example.home.entity.discover.CategoryCardEntity
import com.example.home.entity.discover.SubjectCardEntity
import com.example.home.entity.discover.TopBannerEntity
import com.example.home.entity.nominate.FollowCardEntity
import com.example.home.entity.nominate.SquareCardCollectionEntity
import com.example.home.entity.nominate.TextCardEntity
import com.example.home.entity.nominate.VideoSmallCardEntity
import com.example.home.entity.viewdata.BriefCardViewData
import com.example.home.entity.viewdata.ContentBannerViewData
import com.example.home.entity.viewdata.FollowCardViewData
import com.example.home.entity.viewdata.SingleTitleViewData
import com.example.home.entity.viewdata.TitleCardViewData
import com.example.home.entity.viewdata.TopBannerViewData
import com.example.home.entity.viewdata.VideoCardViewData
import com.example.home.model.HomeDataRepository
import com.example.home.uistate.HomeUiState
import com.example.network.ApiUrl
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.io.Serializable
import javax.inject.Inject

/**
 * 首页ViewModel
 * */
@HiltViewModel
class HomeViewModel @Inject constructor(private val dataRepository: HomeDataRepository) : BaseViewModel<HomeUiState>() {


  private var nextNominatePageUrl = ApiUrl.HOME_NOMINATE_URL
  private var nextDiscoverPageUrl = ApiUrl.HOME_DISCOVER_URL
  private var nextDailyPageUrl = ApiUrl.HOME_DAILY_URL

  /**
   * 加载推荐列表数据
   * */
  fun loadNominateData(isLoadMore : Boolean = false){
      viewModelScope.launch (Dispatchers.IO){
         try {
             //获取接口数据
             var result = if (!isLoadMore) dataRepository.getNominateData() else dataRepository.getNominateData(nextNominatePageUrl)

             var nextPagerParms = result.nextPageUrl.substring(result.nextPageUrl.indexOf("?")+1)
             nextNominatePageUrl = "${ApiUrl.HOME_NOMINATE_URL}?${nextPagerParms}"
             Log.i("LOG_TAG", "下一页请求数据URL地址: $nextNominatePageUrl")
             //判断返回数据
             var itemList = result.itemMap as MutableList<NetDataEntity>
             //数据裁剪
             var parseResultList : List<BaseEntity> =parseNominateViewData(itemList)

             //返回给UI层
             if (parseResultList.isNotEmpty()){
                 unPeekLiveData.postValue(HomeUiState.loadNominateSuccess(parseResultList))
             }else{
                 unPeekLiveData.postValue(HomeUiState.loadNominateFail("数据为空"))
             }
         } catch (e: Exception) {
            e.printStackTrace()
             this.cancel() // 取消协成释放资源
         }
     }
  }

    /**
     * 加载发现列表
     * */
    fun loadDiscoverData(){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //获取接口数据
                var result =dataRepository.getDiscoverData()

                //判断返回数据
                var itemList = result.itemMap as MutableList<NetDataEntity>
                //数据裁剪
                var parseResultList : List<BaseEntity> =parseDiscoverViewData(itemList)

                //返回给UI层
                if (parseResultList.isNotEmpty()){
                    unPeekLiveData.postValue(HomeUiState.loadDiscoverSuccess(parseResultList))
                }else{
                    unPeekLiveData.postValue(HomeUiState.loadDiscoverFail("数据为空"))
                }

            }catch (e: Exception){
                e.printStackTrace()
                this.cancel() // 取消协成释放资源
            }
        }
    }



  /**
   * 获取推荐页面需要字段数据
   * */
  private fun parseNominateViewData(list:MutableList<NetDataEntity>): List<BaseEntity> {
       var resultList = mutableListOf<BaseEntity>()
      list.forEach {
          when(it.type){
                "squareCardCollection"->parseNominateCollectionCard(resultList,it.value)
                "textCard"->parseNominateTitleCard(resultList,it.value)
                "VideoSmallCard"->parseNominateVideoCard(resultList,it.value)
                "followCard"->parseNominateFollowCard(resultList,it.value)
          }
       }
      return resultList
  }



    /**
     * 获取发现页面需要字段数据
     * */
    private fun parseDiscoverViewData(list : MutableList<NetDataEntity>): List<BaseEntity> {
        var resultList = mutableListOf<BaseEntity>()
        list.forEach {
            when(it.type){
                "horizontalScrollCard"->parseDiscoverTopBannerCard(resultList,it.value)
                "specialSquareCardCollection"->parseDiscoverSpecialSquareCard(resultList,it.value)
                "columnCardList"->parseColumnCard(resultList,it.value)
                "textCard"->parseDiscoverTitleCard(resultList,it.value)
                "banner2"->parseDiscoverBannerCard(resultList,it.value)
                "videoSmallCard"->parseNominateVideoCard(resultList,it.value)
                "briefCard"->parseDiscoverFollowCard(resultList,it.value)
            }
        }
        return resultList
    }

    /**
     * 发现页面的顶部Banner数据
     * */
    private fun parseDiscoverTopBannerCard(list: MutableList<BaseEntity>,data : BaseEntity){
        var entity =data as TopBannerEntity
        list.add(TopBannerViewData("https://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png"))
    }

    /**
     * 发现页面的热门分类
     * */
    private fun parseDiscoverSpecialSquareCard(list: MutableList<BaseEntity>, data: BaseEntity){
        list.add(data as CategoryCardEntity)
    }

    /**
     *发现页面里的专题数据
     * */
    private fun parseColumnCard(list: MutableList<BaseEntity>, data: BaseEntity){
        list.add(data as SubjectCardEntity)
    }

    /**
     *发现页面里标题数据
     * */
    private fun parseDiscoverTitleCard(list: MutableList<BaseEntity>, data: BaseEntity){
       var entity = data as TextCardEntity
        list.add(TitleCardViewData(entity.data.text,entity.data.rightText?:""))
    }

    /**
     * 发现页面的中Banner数据
     */
    private fun parseDiscoverBannerCard(list: MutableList<BaseEntity>, data: BaseEntity){
        var entity = data as Banner2CardEntity
        list.add(ContentBannerViewData(entity.data.image))
    }

    private fun parseDiscoverFollowCard(list: MutableList<BaseEntity>, data: BaseEntity){
        var entity =data as BrieCardEntity
        list.add(BriefCardViewData(entity.data.icon,entity.data.title,entity.data.description))
    }








    /**
     * 精选数据
     * */
    private fun parseNominateCollectionCard(resultList: MutableList<BaseEntity>, value: BaseEntity) {
        var entity = value as SquareCardCollectionEntity
        //添加标题数据
        resultList.add(TitleCardViewData(entity.data.header.title,entity.data.header.rightText))
        //解析精选中的视频数据
        entity.data.itemList.forEach {
            parseNominateFollowCard(resultList,it)
        }

    }

    /**
     * 标题数据
     * */
    private fun parseNominateTitleCard(resultList: MutableList<BaseEntity>, value: BaseEntity) {
        var entity = value as TextCardEntity
        resultList.add(SingleTitleViewData(entity.data.text))
    }


    /**
     * 标题数据
     * */
    private fun parseNominateVideoCard(resultList: MutableList<BaseEntity>, value: BaseEntity) {
        var entity = value as VideoSmallCardEntity
        resultList.add(VideoCardViewData(
            entity.data.cover.detail,
            entity.data.duration,
            entity.data.title,
            "${entity.data.author.name} / # ${entity.data.category}",
            entity.data.author.icon,
            entity.data.description,
            entity.data.author.description,
            entity.data.author.name,
            entity.data.playUrl,
            entity.data.cover.blurred,
            entity.data.id,
            entity.data.consumption.collectionCount,
            entity.data.consumption.shareCount
        ))

    }

    /**
     * 标题数据
     * */
    private fun parseNominateFollowCard(resultList: MutableList<BaseEntity>, value: BaseEntity) {
        var entity = value as FollowCardEntity
        resultList.add(FollowCardViewData(
            entity.data.content.data.cover.detail,
            entity.data.content.data.duration,
            entity.data.content.data.author.icon,
            "${entity.data.content.data.author.name}/ # ${entity.data.content.data.category}",
            entity.data.content.data.title,
            entity.data.content.data.description,
            entity.data.content.data.author.description,
            entity.data.content.data.author.name,
            entity.data.content.data.playUrl,
            entity.data.content.data.cover.blurred,
            entity.data.content.data.id,
        ))
    }


    /**
     * 加载每日视频列表
     * */
    fun loadDailyData(isLoadMore : Boolean = false){
        viewModelScope.launch (Dispatchers.IO){
            try {
                //获取接口数据
                var result = if (!isLoadMore) dataRepository.getDailyData() else dataRepository.getDailyData(nextNominatePageUrl)

                var nextPagerParms = result.nextPageUrl.substring(result.nextPageUrl.indexOf("?")+1)
                nextDailyPageUrl = "${ApiUrl.HOME_DAILY_URL}?${nextPagerParms}"
                Log.i("LOG_TAG", "下一页请求数据URL地址: $nextDailyPageUrl")
                //判断返回数据
                var itemList = result.itemMap as MutableList<NetDataEntity>
                //数据裁剪
                var parseResultList : List<BaseEntity> =parseDailyViewData(itemList)

                //返回给UI层
                if (parseResultList.isNotEmpty()){
                    unPeekLiveData.postValue(HomeUiState.loadDailySuccess(parseResultList))
                }else{
                    unPeekLiveData.postValue(HomeUiState.loadDailyrFail("数据为空"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                this.cancel() // 取消协成释放资源
            }
        }
    }

    /**
     * 获取每日页面需要字段数据
     * */
    private fun parseDailyViewData(list:MutableList<NetDataEntity>): List<BaseEntity> {
        var resultList = mutableListOf<BaseEntity>()
        list.forEach {
            when(it.type){
                "textCard"->parseNominateTitleCard(resultList,it.value)
                "followCard"->parseNominateFollowCard(resultList,it.value)
            }
        }
        return resultList
    }




}